//
//  YanRefreshControl.swift
//  SinaWeibo
//
//  Created by mac on 2017/6/7.
//  Copyright © 2017年 mac. All rights reserved.
//

import UIKit

/// 刷新状态切换的临界点
fileprivate let YanRefreshOffset: CGFloat = 126

/// 刷新状态
///
/// - Normal: 普通状态
/// - Pulling: 超过临界点
/// - WillRefresh: 用户超过临界点，并且放手
enum YanRefreshState {
    case Normal
    case Pulling
    case WillRefresh
}

/// 刷新控件 - 负责刷新相关的逻辑处理
class YanRefreshControl: UIControl {

    // MARK: - 属性
    // 滚动视图的父视图，下拉刷新控件应该适用于 UITableView / UICollectionView
    fileprivate weak var scrollView: UIScrollView?
    
    fileprivate lazy var refreshView: YanRefreshView = YanRefreshView.refreshView()
    
    // MARK: - 构造函数
    init() {
        super.init(frame: CGRect())
        
        setupUI()
    }
    
    // xib开发
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI()
    }
    
    /**
     willMove addSubview 方法会调用
     - 当添加到父试图的时候，newSuperview 是父试图
     - 当父试图被移除，newSuperview 是 nil
     */
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        
        // 判断父试图的类型
        guard let sv = newSuperview as? UIScrollView else {
            return
        }
        
        // 记录父视图
        scrollView = sv
        
        // KVO 监听父试图的 contentOffset
        // 在程序中，通常只监听某一个对象的某几个属性，如果属性太多，方法会很乱
        // 观察者模式，在不需要的时候，都要释放
        // - 通知中心：如果不释放，什么也不会发生，但是会有内存泄漏，会有多次注册的可能
        // - KVO：如果不释放，会崩溃
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
        
    }
    
    // MARK: 本视图从父视图上移除
    // 所有的下拉刷新框架都是监听父视图的 contentOffset
    // 所有的框架的KVO监听实现思路都是这个
    override func removeFromSuperview() {
        
        // superView还存在
        superview?.removeObserver(self, forKeyPath: "contentOffset")
        
        super.removeFromSuperview()
        
        // superView不存在
    }
    
    // 所有 KVO 方法会统一调用此方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        
        guard let sv = scrollView else {
            return
        }
        
        
        let height = -(sv.contentInset.top + sv.contentOffset.y)
        
        if height < 0 {
            return
        }
        
        self.frame = CGRect(x: 0, y: -height, width: sv.bounds.width, height: height)
        
        // 传递父视图高度
        if refreshView.refreshState != .WillRefresh {
            refreshView.parentViewHeight = height
        }
        
        
        // 判断临界点
        if sv.isDragging {
            if height > YanRefreshOffset && refreshView.refreshState == .Normal {
                
                refreshView.refreshState = .Pulling
                
            } else if height <= YanRefreshOffset && (refreshView.refreshState == .Pulling) {
                
                refreshView.refreshState = .Normal
                
            }
        } else {
            if refreshView.refreshState == .Pulling {
                
                beginRefreshing()
                
                // 发送刷新数据事件
                sendActions(for: .valueChanged)
            }
        }
        
    }
    
    /// 开始刷新
    func beginRefreshing() {
        // 判断父视图
        guard let sv = scrollView else {
            return
        }
        
        if refreshView.refreshState == .WillRefresh {
            return
        }
        
        // 设置刷新视图的状态
        refreshView.refreshState = .WillRefresh
        
        // 调整表格的间距
        var inset = sv.contentInset
        inset.top += YanRefreshOffset
        sv.contentInset = inset
        
        refreshView.parentViewHeight = YanRefreshOffset
    }
    
    
    /// 结束刷新
    func endRefreshing() {
        
        guard let sv = scrollView else {
            return
        }
        
        // 判断状态，是否正在刷新，如果不是，直接返回
        if refreshView.refreshState != .WillRefresh {
            return
        }
        
        // 恢复刷新视图的状态
        refreshView.refreshState = .Normal
        
        // 恢复表格试图的contentInset
        var inset = sv.contentInset
        inset.top -= YanRefreshOffset
        
        sv.contentInset = inset
        
        
    }

}


extension YanRefreshControl {
    
    fileprivate func setupUI() {
        backgroundColor = superview?.backgroundColor
        
        // 设置超出边界不显示
//        clipsToBounds = true
        
        addSubview(refreshView)
        
        // 自动布局 设置xib控件的自动布局，需要制定宽高约束
        refreshView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refreshView.bounds.width))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refreshView.bounds.height))
    }
    
}
